import type { PlusColumn } from 'plus-pro-components'
import { FlagStatusEnum, SourceStatusEnum, agreementStatusEnum, auditStatusEnum } from '../../constant'

import { useUserStore } from '@fl/store/modules/user'
import { cloneDeep } from 'lodash-es'
// import { useGetContractSupplierLabel } from '@fl/api/mall-api'

import { agreement } from '@fl/api/purchase'
import { useRoute, useRouter } from 'vue-router'
import * as useRules from '../../rules'
import { isAdmin, isPurchaser, isSupplier } from '../../hooks/use-role'

// const isPurchaser = false
// const isSupplier = true
function formatFileList(list) {
    if (list === null || list === undefined)
        return []
    return list.map((file) => {
        return {
            ...file,
            fileName: file.fileName || file.name,
            name: file.name || file.fileName,
            fileUrl: file.fileUrl || file.url,
            url: file.url || file.fileUrl,
        }
    })
}

export function useForm() {
    const { query } = useRoute()
    const { getUserInfo } = useUserStore()

    const { useGetAgreementMetaInfo, useGetContractSupplierLabel } = agreement(isAdmin.value)

    const queryId = ref(query.id)
    const idParams = computed(() => {
        return queryId.value
    })

    const { data: agreementMeta, refetch } = useGetAgreementMetaInfo(idParams)

    const { data: contractSupplierLabel } = useGetContractSupplierLabel()
    const formInstanceRef = ref(null)
    // const validate = formInstanceRef.value.formInstance.formInstance.validate()
    const instanceRef = computed(() => {
        return formInstanceRef.value?.formInstance?.formInstance
    })
    const userInfo = unref(getUserInfo)
    const state = {
        agreementCode: '',
        agreementName: '',
        partyB: '',
        agreementType: 1,
        daterange: null,
        contractFileList: [],
        partyAId: userInfo?.enterpriseId,
        partyA: userInfo?.enterpriseName,
        status: agreementStatusEnum.draft.value,
        source: SourceStatusEnum.jc.value,
        Id: null,
        flag: FlagStatusEnum.yes.value,

    }

    const form = ref({
        ...state,
    })
    const agreementMetaInfo = computed(() => {
        return form.value
    })
    const uploadKey = ref(0)

    // 是否编辑 签约的时候不能编辑
    const onSign = ref(false)

    watch([() => form.value?.partyBId, () => contractSupplierLabel.value], (val) => {
        const [partyBId, contractSupplierLabel] = val
        const supplier = unref(contractSupplierLabel)
        if (partyBId && supplier) {
            form.value.partyB = supplier.find(item => item.value === partyBId)?.label || ''
        }
    }, { deep: true })

    watch(agreementMeta, (newVal) => {
        if (newVal) {
            const data = cloneDeep(newVal)
            data.contractFileList = formatFileList(data.contractFileList)
            data.rejectFileList = formatFileList(data.rejectFileList)

            const isSign = (isPurchaser.value && [agreementStatusEnum.pendingPartyA.value].includes(data.status)) || (isSupplier.value && [agreementStatusEnum.pendingPartyB.value].includes(data.status))

            if (isSign) {
                onSign.value = true
            }

            form.value = data
            uploadKey.value++
        }
    }, { immediate: true })

    const computePartyBOption = computed(() => {
        return contractSupplierLabel.value || []
    })

    // 表单是否需要编辑状态
    const isEditMode = computed(() => {
        //  草稿状态且 不是签约状态才显示编辑按钮 且是自己的row.flag === FlagStatusEnum.yes.value
        return agreementMetaInfo.value?.status === agreementStatusEnum.draft.value && !onSign.value
            && agreementMetaInfo.value?.flag === FlagStatusEnum.yes.value
            // TUDO 未返回字段
        // && 是本人row.flag === FlagStatusEnum.no.value
    })
    const valueTypeMode = (defType) => {
        return isEditMode.value ? defType : 'text'
    }

    const partyBType = computed(() => {
        return isPurchaser.value && agreementStatusEnum.draft.value === agreementMetaInfo.value?.status
            && agreementMetaInfo.value?.source === SourceStatusEnum.jc.value && !onSign.value
            ? 'select'
            : 'text'
    })
    // 草稿状态隐藏签约card
    const hideSignGroup = computed(() => {
        return (agreementMetaInfo.value?.status === agreementStatusEnum.draft.value || agreementMetaInfo.value?.status === agreementStatusEnum.pendingPartyB.value)
    })

    // 展示提交按钮
    const showAddSubmit = computed(() => {
        return agreementMetaInfo.value.Id === null
    })

    const showSignBtns = computed(() => {
        return !showAddSubmit.value
    })

    const showA = computed(() => {
        return [agreementStatusEnum.rejectedByPartyA.value, agreementStatusEnum.effective.value, agreementStatusEnum.disabled.value].includes(agreementMetaInfo.value?.status)
    })
    const bGroup = computed(() => {
        let rejectArr: any[] = [
            {
                colProps: {
                    span: 24,
                },
                label: '签章时间',
                prop: 'partyBSignTime',
                valueType: 'text',
            },
        ]
        if (agreementMetaInfo.value?.status === agreementStatusEnum.rejectedByPartyB.value) {
            rejectArr = [
                {
                    colProps: {
                        span: 24,
                    },
                    label: '驳回理由',
                    prop: 'rejectReason',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '附件B',
                    prop: 'rejectFileListB',
                },
            ]
        }

        return [
            {
                colProps: {
                    span: 24,
                },
                label: '乙方',
                prop: 'partyB',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 24,
                },
                label: '审核结果',
                prop: 'partyBResult',
            },

            ...rejectArr,

        ]
    })

    const aGroup = computed(() => {
        if (!showA.value)
            return []
        let arr: any[] = [
            {
                colProps: {
                    span: 24,
                },
                label: '签章时间',
                prop: 'partyASignTime',
                valueType: 'text',
            },
        ]
        if (agreementMetaInfo.value?.status === agreementStatusEnum.rejectedByPartyA.value) {
            arr = [
                {
                    colProps: {
                        span: 24,
                    },
                    label: '驳回理由',
                    prop: 'rejectReason',
                    valueType: 'text',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '附件',
                    prop: 'rejectFileListA',
                },
            ]
        }
        return [
            {
                colProps: {
                    span: 24,
                },
                label: '甲方',
                prop: 'partyA',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 24,
                },
                label: '审核结果',
                prop: 'partyAResult',
            },
            ...arr,
        ]
    })

    const group = computed(() => {
        const signGroup = {
            title: '签约状态',
            hideInGroup: hideSignGroup,
            columns: [
                ...bGroup.value,
                ...aGroup.value,
            ],
        }

        return [
            {
                title: '签署方信息',
                columns: [
                    {
                        colProps: {
                            span: 12,
                        },
                        label: '甲方',
                        prop: 'partyA',
                        valueType: 'text',
                    },
                    {
                        colProps: {
                            span: 12,
                        },
                        label: '乙方',
                        options: computePartyBOption.value,
                        prop: partyBType.value === 'select' ? 'partyBId' : 'partyB',
                        valueType: partyBType.value,
                        fieldProps: {
                            filterable: true,
                        },
                    },

                ],
            },

            {
                title: '协议信息',
                columns: [
                    {
                        colProps: {
                            span: 24,
                        },
                        label: '协议名称',
                        prop: 'agreementName',
                        valueType: valueTypeMode('input'),
                        fieldProps: {
                            maxlength: 100,
                        },
                    },

                ],
            },

            {
                title: '协议文件',
                columns: [
                    {
                        colProps: {
                            span: 24,
                        },
                        label: '协议文件',
                        prop: 'contractFileList',
                    },

                ],
            },

            { ...signGroup },
        ]
    })

    function reset() {
        form.value = {
            ...state,
        }
    }

    const { partyAId, partyBId, partyA, partyB, contractFileList, agreementName } = useRules
    const rules = computed(() => {
        if (agreementMetaInfo.value?.status === agreementStatusEnum.draft.value) {
            // if (!onSign.value) {
            //     return { }
            // }
            return {
                partyA,
                partyAId,
                partyB,
                partyBId,
                agreementName,
                contractFileList,
            }
        }
        if (isPurchaser.value && agreementMetaInfo.value?.status === agreementStatusEnum.pendingPartyA.value) {
            return {
                partyA,
                partyAId,
                partyB,
                partyBId,
                agreementName,
                contractFileList: useRules.contractFileListWithSign,
            }
        }
        if (isSupplier.value && agreementMetaInfo.value?.status === agreementStatusEnum.pendingPartyB.value) {
            return {
                partyA,
                partyAId,
                partyB,
                partyBId,
                agreementName,
                contractFileList: useRules.contractFileListWithSign,
            }
        }
        return {
            ...useRules,
        }
    })

    return { form, reset, group, onSign, uploadKey, showAddSubmit, showSignBtns, rules, formInstanceRef, instanceRef, refetchAgreen: refetch, queryId }
}

export function useRejectForm() {
    const instanceRejectRef = ref(null)

    const state = {
        remark: '',
        files: [],
        status: auditStatusEnum.no.value,
        id: '',
    }
    const form = ref({ ...state })
    const rules = {
        remark: [
            {
                required: true,
                message: '请输入理由',
            },
        ],
    }
    const schema: PlusColumn[] = [

        {
            label: '驳回理由',
            prop: 'remark',
            valueType: 'textarea',
            labelWidth: '90px',
            fieldProps: {
                maxlength: 200,
                showWordLimit: true,
                autosize: { minRows: 2 },
            },
        },
        {
            label: '附件',
            labelWidth: '90px',
            prop: 'files',
        },
    ]
    const visible = ref(false)

    const resetForm = () => {
        form.value = { ...state }
    }
    const openDialog = () => {
        // resetForm()
        visible.value = true
    }
    const closeDialog = () => {
        resetForm()
        // instanceRef.value && instanceRef.value.formInstance.clearValidate()

        visible.value = false
    }
    return { form, rules, schema, visible, openDialog, closeDialog, instanceRejectRef }
}
